package com.controller;

import com.pojo.ManManufacturer;
import com.pojo.User;
import com.service.ManManufacturerService;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/manufacturer")
public class ManManufacturerController {

    @Autowired
    private ManManufacturerService manufacturerService;
    @Autowired
    private UserService userService;


    @GetMapping("/manInfo")
    public String manInfo(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null){
            return "login";
        }
        user = userService.selectById(user.getId());
        if (user.getManId() == null){
            return "manufacturer/manufacturerAdd";
        }
        ManManufacturer manufacturer = manufacturerService.findById(user.getManId());
        model.addAttribute("manufacturer", manufacturer);
        return "manufacturer/manInfo";
    }

    @PostMapping("/insert")
    public String insert(ManManufacturer manufacturer, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null){
            return "login";
        }
        manufacturerService.insert(manufacturer,user);
        redirectAttributes.addFlashAttribute("successMessage", "品牌商信息添加成功！");
        return "redirect:/manufacturer/manInfo";
    }

    @PostMapping("/update")
    public String update(ManManufacturer manufacturer, RedirectAttributes redirectAttributes) {
        manufacturerService.update(manufacturer);
        redirectAttributes.addFlashAttribute("successMessage", "品牌商信息更新成功！");
        return "redirect:/manufacturer/manInfo";
    }

}
